<template>
  <div class="settings-page">
    <div class="header">
      <el-button @click="$router.go(-1)" :icon="ArrowLeft" circle />
      <h1>设置</h1>
    </div>

    <div class="settings-content">
      <!-- 数据管理 -->
      <el-card class="setting-card">
        <template #header>
          <div class="card-header">
            <span>数据管理</span>
          </div>
        </template>
        
        <div class="setting-section">
          <h3>存储统计</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-value">{{ storageInfo.totalNotes }}</div>
              <div class="stat-label">总笔记数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ storageInfo.totalWords }}</div>
              <div class="stat-label">总字数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ storageInfo.publicNotes }}</div>
              <div class="stat-label">公开笔记</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ storageInfo.totalTags }}</div>
              <div class="stat-label">标签数</div>
            </div>
          </div>
        </div>

        <div class="setting-section">
          <h3>数据备份</h3>
          <div class="action-buttons">
            <el-button @click="exportData" type="primary" :icon="Download" :loading="exporting">
              {{ exporting ? '导出中...' : '导出数据' }}
            </el-button>
          </div>
          <p class="setting-description">
            导出数据将下载一个JSON文件，包含所有笔记。
          </p>
        </div>

        <div class="setting-section">
          <h3>数据清理</h3>
          <el-button @click="showClearConfirm" type="danger" :icon="Delete" :loading="clearing">
            {{ clearing ? '清理中...' : '清空所有数据' }}
          </el-button>
          <p class="setting-description">
            此操作将删除所有笔记，无法恢复。
          </p>
        </div>
      </el-card>

      <!-- 应用设置 -->
      <el-card class="setting-card">
        <template #header>
          <div class="card-header">
            <span>应用设置</span>
          </div>
        </template>
        
        <div class="setting-section">
          <h3>自动保存</h3>
          <el-switch
            v-model="settings.enableAutoSave"
            @change="updateSettings"
          />
          <p class="setting-description">
            启用后，笔记将在30秒无操作后自动保存。
          </p>
        </div>

        <div class="setting-section">
          <h3>默认公开状态</h3>
          <el-switch
            v-model="settings.defaultPublic"
            @change="updateSettings"
          />
          <p class="setting-description">
            新建笔记时是否默认设为公开。
          </p>
        </div>

        <div class="setting-section">
          <h3>字体大小</h3>
          <el-slider
            v-model="settings.fontSize"
            :min="12"
            :max="20"
            :step="1"
            @change="updateSettings"
            show-input
          />
        </div>
      </el-card>

      <!-- 账户信息 -->
      <el-card class="setting-card">
        <template #header>
          <div class="card-header">
            <span>账户信息</span>
          </div>
        </template>
        
        <div class="setting-section">
          <h3>用户信息</h3>
          <div class="user-info">
            <p><strong>用户名:</strong> {{ authStore.user?.username }}</p>
            <p><strong>邮箱:</strong> {{ authStore.user?.email }}</p>
            <p><strong>注册时间:</strong> {{ formatDate(authStore.user?.createdAt) }}</p>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Download, Delete } from '@element-plus/icons-vue'
import { useNotesStore } from '../stores/notesApi'
import { useAuthStore } from '../stores/auth'

interface AppSettings {
  enableAutoSave: boolean
  defaultPublic: boolean
  fontSize: number
}

const notesStore = useNotesStore()
const authStore = useAuthStore()

const exporting = ref(false)
const clearing = ref(false)

// 设置
const settings = ref<AppSettings>({
  enableAutoSave: true,
  defaultPublic: false,
  fontSize: 14
})

// 存储统计信息
const storageInfo = computed(() => {
  const notes = notesStore.notes || []
  const totalWords = notes.reduce((sum, note) => {
    const text = note.content.replace(/<[^>]*>/g, '') // 移除HTML标签
    return sum + text.length
  }, 0)
  
  return {
    totalNotes: notes.length,
    totalWords,
    publicNotes: notes.filter(note => note.isPublic).length,
    totalTags: notesStore.tags?.length || 0
  }
})

onMounted(async () => {
  // 加载笔记数据以获取统计信息
  if (notesStore.notes.length === 0) {
    await notesStore.loadNotes()
  }
  loadSettings()
})

// 加载设置
const loadSettings = () => {
  const stored = localStorage.getItem('web-notes-settings')
  if (stored) {
    try {
      const parsed = JSON.parse(stored)
      settings.value = { ...settings.value, ...parsed }
    } catch (error) {
      console.error('设置加载失败:', error)
    }
  }
}

// 更新设置
const updateSettings = () => {
  localStorage.setItem('web-notes-settings', JSON.stringify(settings.value))
  ElMessage.success('设置已保存')
}

// 导出数据
const exportData = async () => {
  try {
    exporting.value = true
    
    // 确保有最新数据
    await notesStore.loadNotes()
    
    const data = {
      notes: notesStore.notes,
      exportDate: new Date().toISOString(),
      version: '1.0'
    }
    
    const blob = new Blob([JSON.stringify(data, null, 2)], {
      type: 'application/json'
    })
    
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `web-notes-backup-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}

// 显示清空确认对话框
const showClearConfirm = async () => {
  try {
    await ElMessageBox.confirm(
      '此操作将删除所有笔记，无法恢复。确定要继续吗？',
      '清空数据确认',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await clearAllData()
  } catch {
    // 用户取消操作
  }
}

// 清空所有数据
const clearAllData = async () => {
  try {
    clearing.value = true
    
    // 获取所有笔记并逐个删除
    const notes = notesStore.notes || []
    for (const note of notes) {
      await notesStore.deleteNote(note._id)
    }
    
    ElMessage.success('数据已清空')
  } catch (error) {
    console.error('清空数据失败:', error)
    ElMessage.error('清空失败')
  } finally {
    clearing.value = false
  }
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.settings-page {
  width: 100%;
  height: 100%;
  padding: 24px;
  overflow-y: auto;
}

.header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 32px;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}

.header h1 {
  margin: 0;
  color: #303133;
  font-size: 32px;
}

.settings-content {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.setting-card {
  margin-bottom: 0;
}

.card-header {
  font-weight: bold;
  color: #303133;
}

.setting-section {
  margin-bottom: 32px;
}

.setting-section:last-child {
  margin-bottom: 0;
}

.setting-section h3 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.setting-description {
  margin: 8px 0 0 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.user-info p {
  margin: 8px 0;
  color: #606266;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .settings-page {
    padding: 12px;
  }
  
  .header {
    gap: 8px;
    margin-bottom: 24px;
  }
  
  .header h1 {
    font-size: 24px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style> 